import { Modal, Form, Row, message } from 'antd';
import React, { useCallback } from 'react';
import { useRequest } from '@umijs/hooks';
import FormItems from './FormItems';
import { updateResource, addResource } from '../../service';

const Add = function Add({
  visible,
  onClose,
  title = '新增菜单',
  data = {},
  form,
  isEdit = false,
  onSuccess,
}) {
  const { validateFields } = form;

  const { loading, run } = useRequest(isEdit ? updateResource : addResource, {
    manual: true,
    onSuccess() {
      message.success('保存成功!');
      onSuccess();
      onClose();
    },
  });

  const onOk = useCallback(() => {
    console.log(data);
    validateFields().then(params =>
      run({
        ...params,
        ...(data.id
          ? { id: data.id }
          : {
              pid:
                data.selectedKeys && data.selectedKeys.length > 0
                  ? data.selectedKeys[0] === '0-0'
                    ? ''
                    : data.selectedKeys[0]
                  : '',
            }),
      }),
    );
  }, [validateFields, run, data]);

  const formLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      onOk={onOk}
      okButtonProps={{ loading }}
      okText="保存"
      title={title}
      width="72%"
      bodyStyle={{ minHeight: '50vh', display: 'flex', flexDirection: 'column' }}
    >
      <Row justify="center" type="flex" align="middle" style={{ flex: 1 }}>
        <Form style={{ flex: 1 }} {...formLayout}>
          <FormItems formLayout={formLayout} form={form} data={data} isEdit={isEdit} />
        </Form>
      </Row>
    </Modal>
  );
};

export default Form.create()(Add);
